<template>
  <div class="comment-list">
    <van-cell title="全部评论"></van-cell>
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <comment-item
        v-for="(comment, index) in list"
        :key="index"
        :comment="comment"
        @reply-click="$emit('reply-click', $event)"
      />
    </van-list>
    <!-- 评论列表 -->
  </div>
</template>

<script>
import { getComments } from "@/api/comment";
import CommentItem from "./comment-item.vue";
export default {
  name: "CommentList",
  components: { CommentItem },
  props: {
    // 查看文章评论：文章ID
    // 查看评论回复：评论ID
    source: {
      type: [String, Number, Object],
      required: true,
    },
    type: {
      type: String,
      default: "a",
    },
    list: {
      type: Array,
      default: function () {
        //array object的默认值通过函数返回
        return [];
      },
    },
  },
  data() {
    return {
      // list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null,
      limit: 10,
    };
  },

  methods: {
    async onLoad() {
      // 1. 请求获取数据
      const { data } = await getComments({
        type: this.type, // 查看文章评论：a，查看评论回复：c
        source: this.source.toString(),
        offset: this.offset,
        limit: this.limit,
      });

      this.$emit("update-total-count", data.data.total_count);

      const { results } = data.data;
      this.list.push(...results);

      this.loading = false;

      if (results.length) {
        this.offset = data.data.last_id;
      } else {
        this.finished = true;
      }
    },
  },
};
</script>

<style scoped lang="less">
</style>